package com.hq.security;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 配合 DeadLockDemo 重现死锁
 *
 * @author hq
 */
public class DeadLockRunnable implements Runnable {

    /**
     * 标识线程
     */
    int tag;

    public DeadLockRunnable(int tag) {
        this.tag = tag;
    }

    /**
     * 创建2个锁对象。
     */
    static Object object1 = new Object();
    static Object object2 = new Object();

    /**
     * 通过synchronized 实现死锁
     */
    @Override
    public void run() {
        if (tag == 1) {
            synchronized (object1) {
                System.out.println(Thread.currentThread().getName() + "获取到1资源，准备获取2资源");
                synchronized (object2) {
                    System.out.println(Thread.currentThread().getName() + "获取到2资源，完成");
                }
            }
        } else {
            synchronized (object2) {
                System.out.println(Thread.currentThread().getName() + "获取到2资源，准备获取1资源");
                synchronized (object1) {
                    System.out.println(Thread.currentThread().getName() + "获取到1资源，完成");
                }
            }
        }
    }


    static Lock lock = new ReentrantLock(); //(约嗯锤 辣可)
    static Lock lock2 = new ReentrantLock();

    /**
     * 通过lock 实现死锁
     */
    //@Override
    //public void run() {
    //    //线程1执行这个   2个资源相互需要，一直获取不到 导致死锁发生
    //    if(tag == 1){
    //        resource1();
    //    }else{
    //        resource2();
    //    }
    //}
    public static void resource1() {
        lock.lock();
        System.out.println(Thread.currentThread().getName() + "调用resource1");
        resource2();
        lock.unlock();
    }

    public static void resource2() {
        lock2.lock();
        System.out.println(Thread.currentThread().getName() + "调用resource2");
        resource1();
        lock2.unlock();
    }


}
